import { useState } from 'react'
import { Modal, message, Form } from 'antd'

import { IForm } from '@/components'
import { FormItemConfig } from '@/components/FormItem'

import { RecordDetail } from '../type'

interface Props {
	detail?: RecordDetail
	editText?: string
	onEdit: (values: RecordDetail) => Promise<any>
}

const EditNameModal: React.FC<Props> = ({ detail, editText = '编辑', onEdit }) => {
	const [open, setOpen] = useState(false)
	const [form] = Form.useForm()

	const handleOk = async () => {
		try {
			const values = await form.validateFields()
			onEdit(values).then(res => {
				if (res?.code === 0) {
					handleCancel()
				}
			})
		} catch (error) {
			message.warn('信息填写有误！')
		}
	}
	const handleCancel = () => {
		setOpen(false)
	}

	const formItemsConfig: FormItemConfig[] = [
		{
			type: 'input',
			formItemProps: {
				name: 'roleName',
				label: '角色名称',
				initialValue: detail?.roleName,
				rules: [{ required: true }, { max: 50 }],
			},
		},
	]

	return (
		<>
			<div className="link" onClick={() => setOpen(true)}>
				{editText}
			</div>
			{open && (
				<Modal
					title="修改角色名称"
					destroyOnClose
					maskClosable={false}
					open={open}
					onOk={handleOk}
					onCancel={handleCancel}
				>
					<IForm layout="vertical" form={form} formItemsConfig={formItemsConfig}></IForm>
				</Modal>
			)}
		</>
	)
}
export default EditNameModal
